<template>
  <div class="app-container">
    <div id="container"></div>

    <div class="box">
      <el-row>学校招生人数：</el-row>
      <el-row>
        <el-select
          v-model="schoolname_value"
          placeholder="请选择学校"
          class="select"
          size="mini"
        >
          <el-option
            v-for="item in schoolnamearr"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-input v-model="school_input" size="mini" class="input"></el-input>
        <el-button
          type="primary"
          class="btn"
          size="small"
          @click="input_schoolnum()"
          >提交</el-button
        >
      </el-row>
      <el-row>街区适龄人数</el-row>
      <el-row>
        <el-select
          v-model="blockname_value"
          placeholder="请选择街区"
          class="select"
          size="mini"
        >
          <el-option
            v-for="item in blocknamearr"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-input v-model="block_input" size="mini" class="input"></el-input>
        <el-button
          type="primary"
          class="btn"
          size="small"
          @click="input_blocknum()"
          >提交</el-button
        >
      </el-row>
      <el-row>
        <el-button type="primary" class="btn" size="small" @click="clickauto()"
          >自动分区</el-button
        >
        <el-button
          type="primary"
          class="btn"
          size="small"
          @click="clicksystem()"
          >管理系统</el-button
        >
      </el-row>
    </div>
  </div>
</template>



<script>
import {
  getinfo,
  getschoolinfo,
  getschoolnum,
  getblocknum,
  setschoolnum,
  setblocknum,
} from "@/api/school";
export default {
  data() {
    return {
      map: null,
      blockzonearr: [],
      blocksitearr: [],
      blocknamearr: [],
      schoolnamearr: [],
      schoolsitearr: [],
      block_school: [],
      blocknumarr: [],
      schoolnumarr: [],
      school_unfinished: [],
      schoolname_value: "",
      blockname_value: "",
      school_input: "",
      block_input: "",
      polygon: null,
    };
  },
  mounted() {
    this.getinfo();
  },
  watch: {
    schoolname_value: {
      handler(newValue) {
        getschoolnum(newValue).then((res) => {
          let number = res.data.result[0].admission_num;
          this.school_input = number;
        });
      },
    },
    blockname_value: {
      handler(newValue) {
        getblocknum(newValue).then((res) => {
          let number = res.data.result[0].blocknumber;
          this.block_input = number;
        });
      },
    },
  },
  methods: {
    getinfo() {
      getinfo().then((res) => {
        console.log(res);
        let result = res.data.result;
        for (let i = 0; i < result.length; i++) {
          let cen = result[i].blocksite;
          let cenn = cen.substr(1, cen.length - 2);
          let cennn = cenn.split(",");
          // 把所有街区的中心坐标放在blocksitearr数组里
          this.blocksitearr.push(cennn);
          this.blocknamearr.push(result[i].blockname);
          this.blocknumarr.push(result[i].blocknumber);
          let path = "";
          let arr = [];
          path = result[i].blockzone.substr(1, result[i].blockzone.length - 2);
          path = path.split("/");
          path.forEach((item) => {
            let a = item.substr(1, item.length - 2);
            let ar = a.split(",");
            arr.push(ar);
          });
          // 把所有街区的范围坐标放在blockzonearr数组里
          this.blockzonearr.push(arr);
          // console.log("this.blockzonearr", this.blockzonearr);
        }
        getschoolinfo().then((res) => {
          let ress = res.data.result;
          for (let i = 0; i < ress.length; i++) {
            this.schoolnamearr.push(ress[i].schoolname);
            let cen = ress[i].schoolsite;
            let cenn = cen.substr(1, cen.length - 2);
            let cennn = cenn.split(",");
            // 把所有街区的中心坐标放在blocksitearr数组里
            this.schoolsitearr.push(cennn);
            this.schoolnumarr.push(ress[i].admission_num);
            this.school_unfinished.push(ress[i].admission_num);
          }
          this.initAMap();
        });
      });
    },
    initAMap() {
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        layers: [
          // 卫星
          new AMap.TileLayer(),
        ],
        zoom: 13,
        // 设置进入地图，中心为佛山
        // center: [113.11, 23.05],
      });
      // patharr 和 centerarr
      for (let i = 0; i < this.blockzonearr.length; i++) {
        this.createPolyandmark(this.blockzonearr[i]);
      }
      for (let i = 0; i < this.blocksitearr.length; i++) {
        this.createblock(this.blocksitearr[i], this.blocknamearr[i]);
      }
      for (let i = 0; i < this.schoolsitearr.length; i++) {
        this.createschool(this.schoolsitearr[i], this.schoolnamearr[i]);
      }
      // this.fn();
      this.map.setFitView();
    },
    createPolyandmark(path) {
      this.polygon = new AMap.Polygon({
        path: path,
        strokeColor: "#FF33FF",
        strokeWeight: 1,
        // strokeOpacity: 0,
        fillOpacity: 0.2,
        fillColor: "#1791fc",
        zIndex: 50,
        bubble: true,
      });
      this.map.add([this.polygon]);
    },
    createblock(centre, blockname) {
      let marker = new AMap.Marker({
        position: centre, //基点位置
        icon: new AMap.Icon({
          image:
            "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          size: new AMap.Size(25, 34), //图标所处区域大小
          imageSize: new AMap.Size(25, 34), //图标大小
        }),
        offset: new AMap.Pixel(-13, -30), //相对于基点的偏移位置
        // anchor: "bottom-center",
        cursor: "auto",
      });
      // 设置label标签
      // label默认蓝框白底左上角显示，样式className为：amap-marker-label
      marker.setLabel({
        direction: "top",
        offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
        content: `<div class='info'>${blockname}</div>`, //设置文本标注内容
      });
      marker.setMap(this.map);
    },
    createschool(centre, blockname) {
      let marker = new AMap.Marker({
        position: centre, //基点位置
        icon: new AMap.Icon({
          image:
            "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
          size: new AMap.Size(25, 34), //图标所处区域大小
          imageSize: new AMap.Size(25, 34), //图标大小
        }),
        offset: new AMap.Pixel(-13, -30), //相对于基点的偏移位置
        // anchor: "bottom-center",
        cursor: "auto",
      });
      // 设置label标签
      // label默认蓝框白底左上角显示，样式className为：amap-marker-label
      marker.setLabel({
        direction: "top",
        offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
        content: `<div class='info'>${blockname}</div>`, //设置文本标注内容
      });
      marker.setMap(this.map);
    },

    clickauto() {
      getinfo()
        .then((res) => {
          this.map.clearMap();
          for (let i = 0; i < this.blockzonearr.length; i++) {
            console.log("11");
            this.createPolyandmark(this.blockzonearr[i]);
          }
          for (let i = 0; i < this.blocksitearr.length; i++) {
            this.createblock(this.blocksitearr[i], this.blocknamearr[i]);
          }
          for (let i = 0; i < this.schoolsitearr.length; i++) {
            this.createschool(this.schoolsitearr[i], this.schoolnamearr[i]);
          }
          this.blocknumarr = [];
          let result = res.data.result;
          for (let i = 0; i < result.length; i++) {
            this.blocknumarr.push(result[i].blocknumber);
          }
          return getschoolinfo();
        })
        .then((res) => {
          this.schoolnumarr = [];
          this.school_unfinished = [];
          let ress = res.data.result;
          for (let i = 0; i < ress.length; i++) {
            this.schoolnumarr.push(ress[i].admission_num);
            this.school_unfinished.push(ress[i].admission_num);
          }
          this.fn();
        });
    },
    async fn() {
      let Time_list = new Array();
      let Rate = new Array();
      for (let i = 0; i < this.blocknamearr.length; i++) {
        Time_list[i] = new Array(i);
        Rate[i] = new Array(i);
        this.block_school[i] = "";
      }
      function func(lga, lgb) {
        return new Promise((resolve) => {
          let walking = new AMap.Walking({});
          walking.search(lga, lgb, function (status, result) {
            if (status === "complete") {
              resolve(result.routes[0].time);
            }
          });
        });
      }
      for (let i = 0; i < this.blocknamearr.length; i++) {
        for (let j = 0; j < this.schoolnamearr.length; j++) {
          Time_list[i][j] = await func(
            this.blocksitearr[i],
            this.schoolsitearr[j]
          );
        }
      }
      for (let i = 0; i < this.blocknamearr.length; i++) {
        for (let j = 0; j < this.schoolnamearr.length; j++) {
          Rate[i][j] = Time_list[i][j] / this.blocknumarr[i];
        }
      }
      let flagA = new Array();
      let flagB = new Array();
      for (let i = 0; i < this.blocknamearr.length; i++) {
        flagA[i] = 0;
      }
      for (let j = 0; j < this.schoolnamearr.length; j++) {
        flagB[j] = 0;
      }
      let a = 0;
      let b = 0;
      // p循环一次，找到一个最小的Rate[i][j]，找到某一街区对应的学校
      for (let p = 0; p < this.blocknamearr.length; p++) {
        let min = 10000;
        for (let i = 0; i < this.blocknamearr.length; i++) {
          if (flagA[i] === 0) {
            for (let j = 0; j < this.schoolnamearr.length; j++) {
              if (Rate[i][j] < min) {
                min = Rate[i][j];
                a = i;
                b = j;
              }
            }
          }
        }
        if (this.blocknumarr[a] <= this.school_unfinished[b]) {
          flagA[a] = 1;
          flagB[b] = 1;
          this.school_unfinished[b] =
            this.school_unfinished[b] - this.blocknumarr[a];
          this.block_school[a] = this.schoolnamearr[b];
        }
      }
      // 第一阶段划分完，还是有些区域没划到
      for (let i = 0; i < this.blocknamearr.length; i++) {
        let b = 0;
        let k = 0;
        if (flagA[i] === 0) {
          do {
            let min = 1000;
            for (let j = 0; j < this.schoolnamearr.length; j++) {
              if (Rate[i][j] < min) {
                min = Rate[i][j];
                b = j;
              }
            }
            Rate[i][b] = 1001;
            k++;
          } while (this.blocknumarr[i] <= this.school_unfinished[b] || k === 0);
          this.block_school[i] = this.schoolnamearr[b];
          flagA[i] = 1;
        }
      }
      console.log(this.block_school);
      for (let i = 0; i < this.blockzonearr.length; i++) {
        this.createPoly(this.blockzonearr[i], this.block_school[i]);
      }
    },
    createPoly(path, school) {
      if (school === "第一中学") {
        this.polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          // strokeOpacity: 0,
          fillOpacity: 0.6,
          fillColor: "#1791fc",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([this.polygon]);
      } else if (school === "第二中学") {
        this.polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          // strokeOpacity: 0,
          fillOpacity: 0.6,
          fillColor: "#FFDEAD",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([this.polygon]);
      } else if (school === "第三中学") {
        this.polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          // strokeOpacity: 0,
          fillOpacity: 0.6,
          fillColor: "#00FF00",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([this.polygon]);
      } else if (school === "第四中学") {
        this.polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 1,
          // strokeOpacity: 0,
          fillOpacity: 0.6,
          fillColor: "#EE6363",
          zIndex: 50,
          bubble: true,
        });
        this.map.add([this.polygon]);
      }
    },

    input_schoolnum() {
      setschoolnum(this.schoolname_value, this.school_input).then((res) => {
        this.$message({
          message: "提交成功",
          type: "success",
        });
      });
    },
    input_blocknum() {
      setblocknum(this.blockname_value, this.block_input).then((res) => {
        this.$message({
          message: "提交成功",
          type: "success",
        });
      });
    },
    clicksystem() {
      this.$router.push("/management");
    },
  },
};
</script>


<style scoped>
.app-container {
  /* width: 100%;
  height: 100%; */
  position: relative;
}
#container {
  width: 100%;
  height: 620px;
}
.box {
  /* margin-top: 20px; */
  width: 240px;
  height: 180px;
  background-color: white;
  position: absolute;
  top: 0;
  right: 0;
  padding-top: 10px;
  padding-left: 10px;
}
.btn {
  margin-bottom: 10px;
  margin-left: 10px;
}
.amap-marker-label {
  border: 0;
  background-color: transparent;
}
.smallbtn {
  margin-top: 10px;
  margin-left: 0px;
}
.select {
  width: 120px;
}
.input {
  width: 52px;
}
</style>